package com.example.goodpet.activity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.widget.ViewPager2;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.goodpet.R;
import com.example.goodpet.activity.Fragment.UserInfoPetFragment;
import com.example.goodpet.activity.Fragment.UserInfoTieziFragment;
import com.example.goodpet.activity.adapter.MyFragmentVPAdapter;
import com.example.goodpet.bean.Follow;
import com.example.goodpet.bean.UserPetInfo;
import com.example.goodpet.chat.activity.ChatActivity;
import com.example.goodpet.community.bean.UserTieziInfo;
import com.example.goodpet.db.DatabaseHelper;
import com.example.goodpet.my.activity.MyFensiActivity;
import com.example.goodpet.my.activity.MyFollowActivity;
import com.example.goodpet.service.UserService;
import com.example.goodpet.utils.ActivityManager;
import com.example.goodpet.utils.Constants;
import com.example.goodpet.utils.MyApplication;
import com.example.goodpet.utils.RetrofitSingleton;
import com.example.goodpet.utils.SecurityUtils;
import com.example.goodpet.utils.UIUtils;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.zackratos.ultimatebarx.ultimatebarx.java.UltimateBarX;

import java.io.IOException;
import java.sql.Date;
import java.util.ArrayList;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class UserInfoActivity extends FragmentActivity {
    private String TAG=this.getClass().getSimpleName();


    private ViewPager2 vpInfo;
    private TabLayout tabLayout;
    private TabLayoutMediator mediator;
    private CircleImageView portrait;
    private TextView signature;
    private TextView followNumber;
    private TextView fensiNumber;
    private TextView tvSex;
    private Button btnFollow;
    private LinearLayout llFollow;
    private LinearLayout llFensi;
    private FloatingActionButton chat;


    private UserService userService;
    private Retrofit retrofit;

    public UserPetInfo userPetInfo;
    private List<Fragment> fragmentList;

    int follow;
    int fensi;
    public int isFollow;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_info);
        UltimateBarX.statusBarOnly(this)
                .fitWindow(false)
                .light(true)
                .apply();

        ActivityManager.getInstance().addActivity(this);

        tabLayout=findViewById(R.id.tabLayout);
        vpInfo=findViewById(R.id.vpInfo);
        portrait=findViewById(R.id.portrait);
        signature=findViewById(R.id.signature);
        btnFollow=findViewById(R.id.btnFollow);
        tvSex=findViewById(R.id.tvSex);
        followNumber=findViewById(R.id.followNumber);
        fensiNumber=findViewById(R.id.fensiNumber);
        llFollow=findViewById(R.id.llFollow);
        llFensi=findViewById(R.id.llFensi);
        chat=findViewById(R.id.fab);


        retrofit= RetrofitSingleton.getRetrofitNetConfig();
        userService = retrofit.create(UserService.class);
        userPetInfo=getIntent().getParcelableExtra("user");//获取数据

        //加载数据及初始化布局
        Glide.with(this).load(Constants.BASE_URL_IMAGE+userPetInfo.getPortrait()).into(portrait);
        signature.setText(userPetInfo.getSignature());
        tvSex.setText(userPetInfo.getGender()==0?"男":"女");
        //initViewStatus();
        fragmentList=new ArrayList<>();
        fragmentList.add(new UserInfoPetFragment());
        fragmentList.add(new UserInfoTieziFragment());
        vpInfo.setAdapter(new MyFragmentVPAdapter(getSupportFragmentManager(),getLifecycle(),fragmentList));
        //将该用户存入本地数据库
        DatabaseHelper.getInstance(this).getUserDAO().insert(MyApplication.fromUserPetInfoToUser(userPetInfo));
        mediator=new TabLayoutMediator(tabLayout, vpInfo, new TabLayoutMediator.TabConfigurationStrategy() {
            @Override
            public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
                tab.setText(UIUtils.getStringArr(R.array.user_info_tab)[position]);
            }
        });
        mediator.attach();

        initListener();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK)
            if (requestCode == 110) {
                UserTieziInfo info = data.getParcelableExtra("info");
                int position = data.getIntExtra("position", -1);
                if (position != -1 && null != info) {
                    ((UserInfoTieziFragment) fragmentList.get(1)).refresh(position, info);
                }
            }
    }

    @Override
    protected void onResume() {
        //每次进入重新加载个人信息的数据
        super.onResume();
        initViewStatus();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
    }

    private void initListener() {
        chat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ChatActivity.actionStart(UserInfoActivity.this, SecurityUtils.encryptPhoneNumber(userPetInfo.getPhoneNumber()),1);
            }
        });
        llFollow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(UserInfoActivity.this, MyFollowActivity.class);
                intent.putExtra("userId", userPetInfo.getUserId());
                startActivity(intent);
            }
        });
        llFensi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(UserInfoActivity.this, MyFensiActivity.class);
                intent.putExtra("userId",userPetInfo.getUserId());
                startActivity(intent);
            }
        });

        btnFollow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isFollow==1){
                    new AlertDialog.Builder(UserInfoActivity.this)
                            .setTitle("温馨提示")
                            .setMessage("您确定要取消关注吗？")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    //连接服务器,传送用户id
                                    userService.unFollowSomeone(new Follow(0, MyApplication.user.getId(),userPetInfo.getUserId(), null)).enqueue(new Callback<com.example.goodpet.bean.ResponseBody<Object>>() {
                                        @Override
                                        public void onResponse(Call<com.example.goodpet.bean.ResponseBody<Object>> call, Response<com.example.goodpet.bean.ResponseBody<Object>> response) {
                                            com.example.goodpet.bean.ResponseBody<Object> body = response.body();
                                            if (body!=null){
                                                int code = body.getCode();
                                                if (code==200){
                                                    setResult(RESULT_OK);
                                                    isFollow=0;
                                                    fensi=fensi-1;
                                                    //updateFocus(isFollow);
                                                    fensiNumber.setText(String.valueOf(fensi));
                                                    btnFollow.setText("关注");
                                                }else if (code==500){
                                                    UIUtils.toast("服务器发生错误",false);
                                                }
                                            }
                                        }

                                        @Override
                                        public void onFailure(Call<com.example.goodpet.bean.ResponseBody<Object>> call, Throwable t) {
                                            UIUtils.toast("连接服务器失败",false);
                                        }
                                    });

                                }
                            })
                            .setNegativeButton("点错了", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.cancel();
                                }
                            })
                            .setCancelable(false).show();
                }else if (isFollow==0){
                    userService.followSomeone(new Follow(0, MyApplication.user.getId(),userPetInfo.getUserId(), new Date(System.currentTimeMillis()))).enqueue(new Callback<com.example.goodpet.bean.ResponseBody<Object>>() {
                        @Override
                        public void onResponse(Call<com.example.goodpet.bean.ResponseBody<Object>> call, Response<com.example.goodpet.bean.ResponseBody<Object>> response) {
                            com.example.goodpet.bean.ResponseBody<Object> body = response.body();
                            if (body!=null){
                                int code = body.getCode();
                                if (code==200){
                                    setResult(RESULT_OK);
                                    isFollow=1;
                                    fensi=fensi+1;
                                    //updateFocus(isFollow);
                                    fensiNumber.setText(String.valueOf(fensi));
                                    btnFollow.setText("已关注");
                                }else if (code==500){
                                    UIUtils.toast("服务器发生错误",false);
                                }
                            }
                        }

                        @Override
                        public void onFailure(Call<com.example.goodpet.bean.ResponseBody<Object>> call, Throwable t) {
                            UIUtils.toast("连接服务器失败",false);
                        }
                    });
                }

            }
        });
    }

    /**
     * 初始化控件的状态，例如更改关注数量和粉丝数量，更改关注按钮形式
     */
    private void initViewStatus() {
        //特判是自己的情况
        if (MyApplication.user.getId()==userPetInfo.getUserId())btnFollow.setVisibility(View.INVISIBLE);
        //向服务端发送请求
        userService.initUserInfoActivity(MyApplication.user.getId(),userPetInfo.getUserId()).enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<okhttp3.ResponseBody> call, Response<okhttp3.ResponseBody> response) {
                okhttp3.ResponseBody body = response.body();
                if (body!=null){
                    String json = null;
                    try {
                        json = body.string();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    JsonObject jsonObject = JsonParser.parseString(json).getAsJsonObject();
                    follow = jsonObject.get("follow").getAsInt();
                    fensi = jsonObject.get("fensi").getAsInt();
                    isFollow = jsonObject.get("isFollow").getAsInt();
                    followNumber.setText(String.valueOf(follow));
                    fensiNumber.setText(String.valueOf(fensi));
                    if (isFollow==1){
                        btnFollow.setText("取消关注");
                    }else if (isFollow==0){
                        btnFollow.setText("关注");
                    }
                }
            }

            @Override
            public void onFailure(Call<okhttp3.ResponseBody> call, Throwable t) {
                UIUtils.toast("连接服务器失败",false);
                t.printStackTrace();
            }
        });
    }

    /**
     * 更新UserInfoTieziFragment中的
     * @param isFollow
     */
/*    private void updateFocus(int isFollow){
        UserInfoTieziFragment fragment1 = (UserInfoTieziFragment) fragmentList.get(1);
        for (UserTieziInfo userTieziInfo : fragment1.list) {
            userTieziInfo.setFoucs(isFollow==1);
        }
    }*/

}